package com.coldlz.mmp.ssl;

import java.security.KeyPair;
import java.security.PublicKey;
import java.util.Base64;
import java.util.List;

public class KeyPairStr {
    private final KeyPair keyPair;

    public KeyPairStr(KeyPair keyPair) {
        this.keyPair = keyPair;
    }

    public KeyPair getKeyPair() {
        return keyPair;
    }

    public byte[] getPrivateKey() {
        return keyPair.getPrivate().getEncoded();
    }

    public byte[] getPublicKey() {
        return keyPair.getPublic().getEncoded();
    }

    public String getPrivateKeyToBase64() {
        return Base64.getEncoder().encodeToString(getPrivateKey());
    }

    public String getPublicKeyToBase64() {
        return Base64.getEncoder().encodeToString(getPublicKey());
    }

    public String getPrivateKeyToFileStr() {
        StringBuilder key = new StringBuilder();
        key.append("-----BEGIN PRIVATE KEY-----").append('\n');
        for (String line : splitString(getPrivateKeyToBase64())) {
            key.append(line).append('\n');
        }
        key.append("-----END PRIVATE KEY-----").append('\n');
        return key.toString();
    }

    public String getPublicKeyToFileStr() {
        StringBuilder key = new StringBuilder();
        key.append("-----BEGIN PUBLIC KEY-----").append('\n');
        for (String line : splitString(getPublicKeyToBase64())) {
            key.append(line).append('\n');
        }
        key.append("-----END PUBLIC KEY-----").append('\n');
        return key.toString();
    }

    private static List<String> splitString(String str) {
        return Util.splitString(str);
    }

    public PublicKey getPublic() {
        return keyPair.getPublic();
    }

}
